package com.ruoyi.hxf.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.hxf.domain.Education;
import com.ruoyi.hxf.domain.Message;
import com.ruoyi.hxf.domain.Topic;
import com.ruoyi.hxf.service.IMessageService;
import com.ruoyi.hxf.service.ITopicService;
import com.ruoyi.system.domain.vo.SysOssVo;
import com.ruoyi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import net.sf.jsqlparser.statement.select.Top;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.awt.*;
import java.util.Arrays;
import java.util.List;

/**
 * 帖子创建管理
 *
 * @author hxf
 * @date 2023-1-18
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/topic/information")
public class TopicController extends BaseController {
    private final ITopicService iTopicService;
    private final ISysUserService userService;
    private final IMessageService messageService;

    /**
     * 查询帖子管理列表
     */
//    @SaCheckPermission("topic:information:list")
    @GetMapping("/list")
    public TableDataInfo<Topic> list(Topic topic, PageQuery pageQuery) {
        return iTopicService.selectPageTopicList(topic, pageQuery);
    }

    /**
     * 获取帖子管理详细信息
     *
     * @param topicId 主键
     */
//    @SaCheckPermission("topic:information:query")
    @GetMapping("/{topicId}")
    public R<Topic> getInfo(@NotNull(message = "主键不能为空")
                            @PathVariable String topicId) {
        return R.ok(iTopicService.queryById(topicId));
    }

    /**
     * 新增帖子信息
     */
    @Log(title = "新增帖子信息", businessType = BusinessType.INSERT)
    @PostMapping
    public R<Void> add(@Validated @RequestBody Topic topic) {

        return toAjax(iTopicService.insertTopic(topic));
    }

    /**
     * 审核帖子管理
     */
//    @SaCheckPermission("topic:information:edit")
    @Log(title = "帖子管理", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody Topic topic, @RequestBody Message message) {
        if (StringUtils.isNotBlank(message.getMsgContent())) {
            topic.setTopicStatus(String.valueOf(2));
            SysUser sysUser = userService.selectUserById(LoginHelper.getUserId());
            message.setCreateBy(String.valueOf(LoginHelper.getUserId()));
            message.setCreateTime(DateUtils.getNowDate());
            message.setRemark(LoginHelper.getUsername());
            message.setMsgAvatar(sysUser.getAvatar());
            message.setMsgTitle("帖子" + topic.getTopicTitle() + ",审核不通过");
            message.setMsgStatus(0);

            message.setReceiverId(userService.selectUserByIdCreateBy(topic.getCreateBy()));
            messageService.insertMessage(message);
        } else {
            topic.setTopicStatus(String.valueOf(1));
        }
        return toAjax(iTopicService.updateByTopic(topic));
    }

    /**
     * 删除帖子管理
     *
     * @param topicIds 主键串
     */
//    @SaCheckPermission("topic:information:remove")
    @Log(title = "帖子管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{topicIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable String[] topicIds) {
        return toAjax(iTopicService.deleteWithValidByIds(Arrays.asList(topicIds), true));
    }

    /**
     * 查询帖子管理列表
     */
    @GetMapping("/AppList")
    public TableDataInfo<Topic> AppList(Topic topic, PageQuery pageQuery) {
        TableDataInfo<Topic> topicTableDataInfo = iTopicService.selectAppPageTopicList(topic, pageQuery);
        Long userId = LoginHelper.getUserId();
        for (Topic row : topicTableDataInfo.getRows()) {
            if ("1".equals(iTopicService.selectCollectionByUserIdAndTopicId(userId, row.getTopicId(), "0"))) {
                row.setTopicCollection("1");
            } else {
                row.setTopicCollection("0");
            }
        }
        return topicTableDataInfo;
    }

    /**
     * 喜欢和取消喜欢
     */
    @Log(title = "喜欢和取消喜欢", businessType = BusinessType.UPDATE)
    @PutMapping("/{topicId}/{userId}/{status}/{type}")
    public R<Void> likeEdit(@PathVariable("topicId") String topicId, @PathVariable("userId") String userId, @PathVariable("status") String status, @PathVariable("type") String type) {
        if (iTopicService.selectTopicLike(topicId, String.valueOf(LoginHelper.getUserId()), type)) {
            iTopicService.updateTopicLike(topicId, String.valueOf(LoginHelper.getUserId()), status, type);
        } else {
            iTopicService.insertTopicLike(topicId, String.valueOf(LoginHelper.getUserId()), status, type);
        }

        Topic topic = iTopicService.queryById(topicId);
        if (status.equals("1")) {
            topic.setTopicLikes(topic.getTopicLikes() + 1);
        } else {
            topic.setTopicLikes(topic.getTopicLikes() - 1);
        }
        topic.setUpdateBy(null);
        topic.setUpdateTime(null);
        return toAjax(iTopicService.updateByTopic(topic));
    }

    /**
     * 阅读
     */
    @Log(title = "阅读", businessType = BusinessType.UPDATE)
    @PutMapping("/read/{topicId}")
    public R<Void> readEdit(@PathVariable("topicId") String topicId) {
        Topic topic = iTopicService.queryById(topicId);
        topic.setReadCount(topic.getReadCount() + 1);
        topic.setUpdateBy(null);
        topic.setUpdateTime(null);
        return toAjax(iTopicService.updateByTopic(topic));
    }

    /**
     * 查询帖子管理列表
     */
    @GetMapping("/AppMyList")
    public TableDataInfo<Topic> AppMyList(Topic topic, PageQuery pageQuery) {
        topic.setCreateBy(LoginHelper.getUsername());
        TableDataInfo<Topic> topicTableDataInfo = iTopicService.selectMyAppPageTopicList(topic, pageQuery);
        Long userId = LoginHelper.getUserId();
        for (Topic row : topicTableDataInfo.getRows()) {
            if ("1".equals(iTopicService.selectCollectionByUserIdAndTopicId(userId, row.getTopicId(), "0"))) {
                row.setTopicCollection(iTopicService.selectCollectionByUserIdAndTopicId(userId, row.getTopicId(), "0"));
            } else {
                row.setTopicCollection("0");
            }
        }
        return topicTableDataInfo;
    }

    /**
     * 修改帖子
     */
    @Log(title = "修改帖子", businessType = BusinessType.UPDATE)
    @PutMapping("/update")
    public R<Void> updateEdit(@RequestBody Topic topic) {
        topic.setTopicStatus(String.valueOf(0));
        return toAjax(iTopicService.updateTopicByTopicId(topic));
    }
}
